/*
   Copyright 2022 cmanlh

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
import JscDatabind from './databind.js';

export default class JscLoopFor extends JscDatabind {
    static get observedAttributes() { return ['jscbind', 'delnode'] }

    #itemTemplate;
    #jscBind;
    #value = [];
    #itemCount = 0;
    #delNode;

    constructor() {
        super();
        this.#init();
    }

    set value(val) {
        if (!(val instanceof Array)) {
            throw new Error("For node only accepts array as value to bind.");
        }
        if (this.#value === val && val.length === this.#itemCount) {
            return;
        }
        this.#value = val;
        if (this.#value.length != this.#itemCount) {
            this.#itemCount = this.#value.length;
        }
        this.reRender(Date.now());
        this.updateBindValue(this.#jscBind, this.#value);
    }

    get value() {
        return this.#value;
    }

    /**
     * rerender the node
     */
    reRender(batchStamp) {
        let itemList = this.querySelectorAll('jsc-loop-item');
        if (itemList.length > this.#itemCount) {
            const maxIdx = this.#itemCount - 1;
            for (let index = itemList.length - 1; index >= 0; index--) {
                const item = itemList[index];
                if (index > maxIdx) {
                    item.remove();
                } else {
                    item.setAttribute('idx', index);
                }
            }
        } else if (itemList.length < this.#itemCount) {
            for (let index = itemList.length - 1; index >= 0; index--) {
                itemList[index].setAttribute('idx', index);
            }
            let newNodes = document.createDocumentFragment();
            for (let index = itemList.length; index < this.#itemCount; index++) {
                let newChild = this.#itemTemplate.cloneNode(true);
                newChild.parentBind = this.bind;
                newChild.parentBindExp = this.#jscBind;
                newChild.idx = index;
                newNodes.appendChild(newChild);
            }
            this.appendChild(newNodes);
        }

        this.querySelectorAll('jsc-loop-item').forEach((node) => node.bindRefresh(batchStamp));
    }

    bindRefresh(bindStamp) {
        if (super.bindRefresh(bindStamp)) {
            if (null != this.bind && null != this.#jscBind) {
                this.#value = this.fetchBindValue(this.#jscBind);
                if (null != this.#value && this.#value instanceof Array) {
                    if (this.#value.length != this.#itemCount) {
                        this.#itemCount = this.#value.length;
                    }
                } else {
                    this.#value = [];
                    this.#itemCount = 0;
                }
                this.reRender(bindStamp);
            }
        }
    }

    #addLoopItem() {
        this.#itemCount += 1;
        this.reRender(Date.now());
    }

    addLoopItemAtTail(data) {
        this.#value.push(data);
        this.#addLoopItem();
    }

    addLoopItemBeforeTail(data) {
        this.#value.splice(this.#itemCount - 1, 0, data);
        this.#addLoopItem();
    }

    addLoopItemAtHead(data) {
        this.#value.shift(data);
        this.#addLoopItem();
    }

    addLoopItemAfterHead(data) {
        this.#value.splice(1, 0, data);
        this.#addLoopItem();
    }

    #removeLoopItem(item) {
        this.#value.splice(item.getAttribute('idx'), 1);
        this.#itemCount -= 1;
        this.reRender(Date.now());
    }

    connectedCallback() {
        let self = this;
        self.#itemTemplate = self.querySelector('jsc-loop-item');
        self.#itemTemplate.remove();
        self.addEventListener('click', function (e) {
            if (e.target.classList && e.target.classList.contains(self.#delNode)) {
                let el = e.target.parentElement;
                while (el) {
                    if ('JSC-LOOP-ITEM' === el.nodeName) {
                        self.#removeLoopItem(el);
                        break;
                    } else {
                        el = el.parentElement;
                    }
                }
            }
        });
    }

    attributeChangedCallback(name, oldValue, newValue) {
        switch (name) {
            case 'jscbind': {
                if (oldValue != newValue) {
                    this.#jscBind = newValue;
                }
                break;
            }
        }
    }

    #init() {
        this.#jscBind = this.getAttribute('jscbind');
        this.#delNode = this.getAttribute('delnode');
    }
}

if (!customElements.get('jsc-loop-for')) {
    window.customElements.define("jsc-loop-for", JscLoopFor);
}